//
// Created by pengx on 2025/9/26.
//

#include "sdp_parser.hpp"
#include "base_config.hpp"
#include <android/log.h>

#include <sstream>

#define TAG "JNI-SdpParser"
#define LGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)

SdpStruct SdpParser::parse(const std::string &sdp) {
    SdpStruct sdp_struct;

    // 提取 c= 行的 IP
    std::regex c_regex("c=IN IP4 ([\\d\\.]+)");
    std::smatch c_match;
    if (regex_search(sdp, c_match, c_regex) && c_match.size() > 1) {
        sdp_struct.remote_ip = c_match[1].str();
    }

    // 提取 m=video 行的端口
    std::regex m_regex("m=video (\\d+)");
    std::smatch m_match;
    if (regex_search(sdp, m_match, m_regex) && m_match.size() > 1) {
        sdp_struct.remote_port = stoi(m_match[1].str());
    }

    // y= 字段（GB28181 SSRC）
    std::regex y_regex(R"(y=(\S+))");
    std::smatch y_match;
    if (std::regex_search(sdp, y_match, y_regex) && y_match.size() > 1) {
        sdp_struct.ssrc = y_match[1].str();
    }

    return sdp_struct;
}

std::string SdpParser::buildSdpAnswer(const std::string &device_code,
                                      const std::string &local_ip,
                                      int &local_port,
                                      const std::string &ssrc) {
    std::ostringstream sdp;
    sdp << "v=0\r\n"
            << "o=" << device_code << " 0 0 IN IP4 " << local_ip << "\r\n"
        << "s=Play\r\n"
            << "c=IN IP4 " << local_ip << "\r\n"
        << "t=0 0\r\n"
            << "m=video " << local_port << " RTP/AVP 96\r\n"
            << "a=sendonly\r\n"
        << "a=rtpmap:96 PS/90000\r\n"
        << "y=" << ssrc << "\r\n";
    LGD("%s", sdp.str().c_str());
    return sdp.str();
}